<template>
  <div class="profile-container">
    <div class="profile-header">
      <h2>个人信息</h2>
      <button
        class="edit-button"
        :class="{ 'active': isEditing }"
        @click="toggleEdit"
      >
        {{ isEditing ? '取消' : '编辑' }}
      </button>
    </div>
    
    <div class="profile-content">
      <!-- 头像部分 -->
      <div class="avatar-section">
        <div class="avatar-container">
          <div class="avatar-upload">
            <img v-if="userAvatar" :src="userAvatar" alt="用户头像" />
            <div v-else class="default-avatar">
              {{ getAvatarText }}
            </div>
            <input
              v-if="isEditing"
              type="file"
              id="avatar-upload"
              accept="image/*"
              @change="handleAvatarUpload"
              class="avatar-input"
            />
            <label
              v-if="isEditing"
              for="avatar-upload"
              class="avatar-upload-overlay"
            >
              <span>更换头像</span>
            </label>
          </div>
        </div>
      </div>
      
      <!-- 基本信息表单 -->
      <form class="profile-form" @submit.prevent="handleSubmit">
        <div class="form-grid">
          <div class="form-group">
            <label>用户名</label>
            <input
              type="text"
              v-model="profileForm.username"
              :disabled="!isEditing"
              class="form-input"
              :class="{ 'disabled': !isEditing }"
            />
          </div>
          
          <div class="form-group">
            <label>邮箱</label>
            <input
              type="email"
              v-model="profileForm.email"
              :disabled="!isEditing"
              class="form-input"
              :class="{ 'disabled': !isEditing }"
            />
          </div>
          
          <div class="form-group">
            <label>手机号码</label>
            <input
              type="tel"
              v-model="profileForm.phone"
              :disabled="!isEditing"
              class="form-input"
              :class="{ 'disabled': !isEditing }"
            />
          </div>
          
          <div class="form-group">
            <label>注册时间</label>
            <input
              type="text"
              :value="formatDate(userStore.userInfo.createdAt)"
              disabled
              class="form-input disabled"
            />
          </div>
          
          <div class="form-group full-width">
            <label>个人简介</label>
            <textarea
              v-model="profileForm.bio"
              :disabled="!isEditing"
              rows="4"
              class="form-textarea"
              :class="{ 'disabled': !isEditing }"
              placeholder="介绍一下自己吧..."
            ></textarea>
          </div>
        </div>
        
        <!-- 保存按钮 -->
        <div v-if="isEditing" class="form-actions">
          <button type="button" class="cancel-button" @click="toggleEdit">取消</button>
          <button type="submit" class="save-button" :disabled="isSubmitting">
            {{ isSubmitting ? '保存中...' : '保存' }}
          </button>
        </div>
      </form>
      
      <!-- 提示信息 -->
      <div v-if="successMessage" class="success-message">{{ successMessage }}</div>
      <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
    </div>
    
    <!-- 账号安全设置 -->
    <div class="security-section">
      <h3>账号安全</h3>
      <div class="security-options">
        <div class="security-item">
          <div class="security-info">
            <h4>修改密码</h4>
            <p>定期修改密码可以保障账号安全</p>
          </div>
          <button class="security-button" @click="goToChangePassword">修改</button>
        </div>
        
        <div class="security-item">
          <div class="security-info">
            <h4>绑定手机</h4>
            <p>{{ userStore.userInfo.phone ? '已绑定: ' + userStore.userInfo.phone : '未绑定手机' }}</p>
          </div>
          <button class="security-button" @click="goToBindPhone">
            {{ userStore.userInfo.phone ? '更换' : '绑定' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useUserStore } from '../stores/user'

const userStore = useUserStore()

const isEditing = ref(false)
const isSubmitting = ref(false)
const successMessage = ref('')
const errorMessage = ref('')
const userAvatar = ref('')

// 初始化表单数据
const profileForm = ref({
  username: '',
  email: '',
  phone: '',
  bio: ''
})

// 监听用户信息变化，更新表单数据
watch(() => userStore.userInfo, (newUserInfo) => {
  profileForm.value = {
    username: newUserInfo.username || '',
    email: newUserInfo.email || '',
    phone: newUserInfo.phone || '',
    bio: newUserInfo.bio || ''
  }
  userAvatar.value = newUserInfo.avatar || ''
}, { immediate: true, deep: true })

// 获取头像显示文字
const getAvatarText = computed(() => {
  if (profileForm.value.username) {
    return profileForm.value.username.charAt(0).toUpperCase()
  }
  return '?'
})

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 切换编辑状态
const toggleEdit = () => {
  isEditing.value = !isEditing.value
  // 清除提示信息
  successMessage.value = ''
  errorMessage.value = ''
}

// 处理头像上传
const handleAvatarUpload = (event) => {
  const file = event.target.files[0]
  if (file) {
    // 这里应该上传到服务器，现在只是本地预览
    const reader = new FileReader()
    reader.onload = (e) => {
      userAvatar.value = e.target.result
    }
    reader.readAsDataURL(file)
  }
}

// 提交表单
const handleSubmit = async () => {
  isSubmitting.value = true
  successMessage.value = ''
  errorMessage.value = ''
  
  try {
    // 准备提交的数据
    const updateData = {
      ...profileForm.value,
      avatar: userAvatar.value
    }
    
    const result = await userStore.updateProfile(updateData)
    
    if (result.success) {
      successMessage.value = '个人信息更新成功！'
      isEditing.value = false
    } else {
      errorMessage.value = '更新失败，请稍后重试'
    }
  } catch (error) {
    console.error('更新个人信息错误:', error)
    errorMessage.value = '更新失败，请稍后重试'
  } finally {
    isSubmitting.value = false
  }
}

// 跳转到修改密码页面
const goToChangePassword = () => {
  alert('跳转到修改密码页面')
  // 实际项目中应该使用router.push()
}

// 跳转到绑定手机页面
const goToBindPhone = () => {
  alert('跳转到绑定手机页面')
  // 实际项目中应该使用router.push()
}
</script>

<style scoped>
.profile-container {
  padding: 32px;
}

.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.profile-header h2 {
  margin: 0;
  font-size: 22px;
  color: #333;
}

.edit-button {
  padding: 8px 20px;
  background-color: #4285f4;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.edit-button:hover {
  background-color: #3367d6;
}

.edit-button.active {
  background-color: #f44336;
}

/* 头像部分 */
.avatar-section {
  display: flex;
  justify-content: center;
  margin-bottom: 32px;
}

.avatar-container {
  position: relative;
}

.avatar-upload {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  overflow: hidden;
  background-color: #f0f0f0;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-upload img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.default-avatar {
  font-size: 48px;
  font-weight: 600;
  color: #4285f4;
}

.avatar-input {
  display: none;
}

.avatar-upload-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  text-align: center;
  padding: 8px;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.avatar-upload:hover .avatar-upload-overlay {
  opacity: 1;
}

/* 表单样式 */
.profile-form {
  max-width: 800px;
  margin: 0 auto;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.form-group {
  margin-bottom: 0;
}

.form-group.full-width {
  grid-column: 1 / -1;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #555;
  font-size: 14px;
}

.form-input,
.form-textarea {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 16px;
  transition: border-color 0.3s ease;
  box-sizing: border-box;
}

.form-input:focus,
.form-textarea:focus {
  outline: none;
  border-color: #4285f4;
  box-shadow: 0 0 0 2px rgba(66, 133, 244, 0.1);
}

.form-input.disabled,
.form-textarea.disabled {
  background-color: #f5f5f5;
  color: #666;
  cursor: not-allowed;
}

.form-textarea {
  resize: vertical;
  min-height: 100px;
}

/* 表单操作按钮 */
.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 32px;
  grid-column: 1 / -1;
}

.cancel-button {
  padding: 10px 24px;
  background-color: #f5f5f5;
  color: #666;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.cancel-button:hover {
  background-color: #e0e0e0;
}

.save-button {
  padding: 10px 24px;
  background-color: #4285f4;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.save-button:hover:not(:disabled) {
  background-color: #3367d6;
}

.save-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

/* 提示信息 */
.success-message {
  padding: 12px;
  background-color: #efe;
  color: #388e3c;
  border-radius: 6px;
  font-size: 14px;
  margin-top: 20px;
  text-align: center;
}

.error-message {
  padding: 12px;
  background-color: #fee;
  color: #d32f2f;
  border-radius: 6px;
  font-size: 14px;
  margin-top: 20px;
  text-align: center;
}

/* 账号安全部分 */
.security-section {
  margin-top: 40px;
  padding-top: 24px;
  border-top: 1px solid #eee;
}

.security-section h3 {
  margin: 0 0 24px 0;
  font-size: 20px;
  color: #333;
}

.security-options {
  max-width: 800px;
  margin: 0 auto;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 16px;
}

.security-info h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  color: #333;
}

.security-info p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.security-button {
  padding: 8px 20px;
  background-color: #4285f4;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.security-button:hover {
  background-color: #3367d6;
}

@media (max-width: 768px) {
  .profile-container {
    padding: 20px;
  }
  
  .form-grid {
    grid-template-columns: 1fr;
  }
  
  .security-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .security-button {
    align-self: flex-end;
  }
}
</style>